<script setup>
  import {useRouter} from "vue-router";
  import {onBeforeUnmount, onMounted, ref} from "vue";
  import axios from "axios";
  import flvjs from "flv.js";

  const router = useRouter();

  const cameraId = ref("");
  const videoUrl = ref("");
  const player = ref(null);

  const webrtcServer = ref(null);
  const flvplayer = ref(null);

  const getPlayUrl = (cameraId) => {
    axios.get("/api/getpreviewurls/" + cameraId )
        .then(res => {
          console.log(res.data)
          if(res.data.hasOwnProperty("code") && res.data.code == 0){
            // videoUrl.value = encodeURIComponent(res.data.data.url);
            videoUrl.value = res.data.data.url;
            console.log(res.data.data.url)

            webrtcServer.value = new WebRtcStreamer(
                "video-player",
                "http://dv.glunicom.com:8200"
                // "http://localhost:3721"
            )
            webrtcServer.value.connect(videoUrl.value)
            // axios.get("/api/flv/hls/stream?url="+videoUrl.value)
            //     .then(res => {console.log(res)})
            //     .catch(err=>{
            //       console.log(err);
            //     })
            // flvplayer.value = flvjs.createPlayer({
            //   type: "flv",
            //   isLive: true,
            //   hasAudio: false,
            //   url: "http://localhost:8801/flv/hls/stream?url=" + videoUrl.value
            // })
            // flvplayer.value.attachMediaElement(document.getElementById("flv-player"));
            // flvplayer.value.load();
            // flvplayer.value.play();

          }
        })
        .catch(err => {
          console.log(err);
        })
        .finally(() => {

        })
  }


  onMounted(() => {
    console.log(router.currentRoute.value)
    cameraId.value = router.currentRoute.value.query.cameraId;
    getPlayUrl(cameraId.value);
  })

  onBeforeUnmount(() => {
    if(webrtcServer.value)
    {
      webrtcServer.value.disconnect();
      webrtcServer.value = null;

    }
    if(flvplayer.value)
    {
      flvplayer.value.pause();
      flvplayer.value.unload();
      flvplayer.value.detachMediaElement();
      flvplayer.value.destroy();
      flvplayer.value = null;
    }
  })

</script>

<template>
<!--  <div id="player"></div>-->
<!--  {{cameraId}}-->
  <video
      id="video-player"
      controls
      autoplay
      width="100%"
  >
  </video>
<!--  <video id="flv-player" controls autoplay width="600" height="400">-->

<!--  </video>-->

</template>

<style scoped>

</style>